package main

import (
	"example-damo/global"
	"example-damo/pro"
	"fmt"
	"google.golang.org/grpc"
	"log"
	"net"
	"sync"
	"time"
)

const PORT = ":50051"

type server struct {
	*pro.UnimplementedGreeterServer
}

// 服务端 单向流
func (s *server) GetStream(req *pro.StreamReqData, res pro.Greeter_GetStreamServer) error {
	for _, data := range global.MessageInfo {
		res.Send(&pro.StreamResData{Data: data})
		time.Sleep(1 * time.Second)
	}
	fmt.Println("11111111")
	return nil
}

// 客户端 单向流
func (this *server) PutStream(cliStr pro.Greeter_PutStreamServer) error {
	for {
		if tem, err := cliStr.Recv(); err == nil {
			log.Println(tem)
			global.MessageInfo = append(global.MessageInfo, tem.Data)
		} else {
			log.Println("break, err :", err)
			break
		}
	}

	return nil
}

// 客户端服务端 双向流
func (this *server) AllStream(allStr pro.Greeter_AllStreamServer) error {

	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		for {
			data, _ := allStr.Recv()
			log.Println(data)
		}
		wg.Done()
	}()

	go func() {
		for {
			allStr.Send(&pro.StreamResData{Data: "server send ssss"})
			time.Sleep(time.Second)
		}
		wg.Done()
	}()

	wg.Wait()
	return nil
}

func main() {
	//监听端口
	lis, err := net.Listen("tcp", PORT)
	if err != nil {
		return
	}
	global.ServerAddress[1] = "localhost:50051"
	//创建一个grpc 服务器
	s := grpc.NewServer()
	//注册事件
	pro.RegisterGreeterServer(s, &server{})
	//处理链接
	s.Serve(lis)
}
